<template>
  <div>
    <div
      data-v-d3f53d98=""
      class="el-select el-select--small"
      @click="visible = !visible"
    >
      <div v-if="!single"
           class="el-select__tags"
           ref="el_select__tags"
           style="width: 100%; padding-right: 35px"
      >
        <span>
          <span
            v-for="(item, index) in values"
            :key="index"
            class="el-tag el-tag--info el-tag--mini el-tag--light"
          >
            <span class="el-select__tags-text">{{ item.userName }}</span>
            <i
              class="el-tag__close el-icon-close"
              @click.stop="remove(item, index)"
            ></i>
          </span>
        </span>
      </div>
      <div class="el-input el-input--small el-input--suffix">
        <input
          type="text"
          readonly="readonly"
          v-model="singleValue.userName"
          autocomplete="off"
          :placeholder="values.length > 0 ? '' : $t('public.select_holder')"
          class="el-input__inner"
          :style="{ height: inputHeight + 'px' }"
        />
        <span class="el-input__suffix">
          <span class="el-input__suffix-inner">
            <i class="el-select__caret el-input__icon el-icon-arrow-up"></i>
          </span>
        </span>
      </div>
    </div>
    <el-dialog
      :visible.sync="visible"
      width="1100px"
      custom-class="dialog-class"
      append-to-body
      :fullscreen="fullscreen"
      :close-on-click-modal="false"
    >
      <div slot="title" class="dialog-title">
        <span>组织选择</span>
        <i
          class="s-icon"
          :class="{
            'el-icon-full-screen': !fullscreen,
            'el-icon-copy-document': fullscreen,
          }"
          @click="fullscreen = !fullscreen"
        ></i>
      </div>
      <el-container>
        <el-header>
          <div class="data-wrap">
            <h5>已选择:</h5>
            <div class="data-content">
              <el-tag
                v-if="single && data &&  data.userName"
                class="mr10"
                size="small"
                :disable-transitions="transition"
              >{{ data.userName }}</el-tag>
              <el-tag
                v-if="data.length > 0 && !single"
                v-for="(item, index) in data"
                :key="index"
                class="mr10"
                size="small"
                :disable-transitions="transition"
                closable
                @close="removeTag(item, index)"
              >{{ item.userName }}</el-tag>
              <span v-if="!single && data.length == 0" class="holder-select">请选择</span>
              <span v-if="single && !(data && data.userName)" class="holder-select">请选择</span>
            </div>
          </div>
        </el-header>
        <el-main>
          <div class="opera-body">
            <div class="opera-dept">
              <!--部门数据-->
              <div class="head-container">
                <el-input
                  v-model="deptName"
                  :placeholder="
                    $t('public.placeholder', {
                      placeholder: $t('deptManage.deptName'),
                    })
                  "
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  style="margin-bottom: 20px"
                />
              </div>
              <div class="head-container">
                <el-tree
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  default-expand-all
                  @node-click="handleNodeClick"
                />
              </div>
            </div>
            <div class="opera-table">
              <el-form
                class="query-form"
                :model="queryParams"
                ref="queryForm"
                :inline="true"
                label-width="68px"
              >
                <el-form-item
                  :label="$t('userManage.userName')"
                  prop="userName"
                  size="small"
                >
                  <el-input
                    v-model="queryParams.userName"
                    :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('userManage.userName'),
                      })
                    "
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item
                  :label="$t('userManage.loginName')"
                  prop="loginName"
                  size="small"
                >
                  <el-input
                    v-model="queryParams.loginName"
                    :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('userManage.loginName'),
                      })
                    "
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item size="small" style="float: right">
                  <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                  >{{ $t("public.reset") }}</el-button
                  >
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                  >{{ $t("public.search") }}</el-button
                  >
                </el-form-item>
              </el-form>
              <el-table
                height="295px"
                stripe
                ref="table"
                :data="tableData"
                @row-click="rowClick"
                @selection-change="selectionChange"
                @current-change="handleSelectChange"
                border
                style="width: 100%"
              >
                <el-table-column v-if="!single" type="selection" width="55" align="center" />
                <el-table-column v-if="single"  width="55" align="center">
                  <template slot-scope="scope">
                    <el-radio v-model="data" :label="scope.row">{{""}}</el-radio>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('public.serialNum')"
                  type="index"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span>{{
                        (queryParams.pageNum - 1) * queryParams.pageSize +
                        scope.$index +
                        1
                      }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="tenantCode"
                  label="工号"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="userName"
                  label="姓名"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="dept.deptName"
                  label="部门"
                  align="center"
                >
                </el-table-column>
                <el-table-column prop="status" align="center" label="状态">
                  <template slot-scope="scope">
                    {{ scope.row.status == "0" ? "正常" : "停用" }}
                  </template>
                </el-table-column>
                <el-table-column prop="email" width="300" label="邮箱">
                </el-table-column>
              </el-table>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[10, 20, 50, 100]"
                :small="true"
                background
                style="text-align: right; margin: 8px 0 0"
                layout=" prev, pager, next, sizes"
                :total="total"
              >
              </el-pagination>
            </div>
          </div>
        </el-main>
        <el-footer height="34px">
          <div class="dialog-footer">
            <el-button @click="cancel" size="small" icon="el-icon-close">{{
                $t("btn.cancel")
              }}</el-button>
            <el-button
              type="primary"
              @click="submitForm"
              size="small"
              icon="el-icon-check"
            >{{ $t("btn.confirm") }}</el-button
            >
          </div>
        </el-footer>
      </el-container>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 人员按部门多选组件
 * author: fenghuan@enjoysoftware.cn
 * date: 2022/02/16
 * use: <enjoy-person-dropdown v-model="persons"> </enjoy-person-dropdown>
 * person: [{id:1,name:'张三'}, ...]
 */
import { listUser } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import { find } from "lodash";
export default {
  name: "EnjoyPersonDropdown",
  props: {
    /* 多选 外部v-model传入的人员 例如：v-model=[{userId:1, userName:'张三'}]  单选 是 {userId:1, userName:'张三'} */
    value: [ Object, Array],
    /** 单选 默认不传为多选 */
    single:{
      type: Boolean,
    }
  },
  data() {
    return {
      visible: false, // 是否打开了弹框
      fullscreen: false, // 是否全屏
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 部门名称
      deptName: undefined,
      data: undefined, //已选择项
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        loginName: undefined,
        deptId: undefined,
      },
      transition: true,
      total: 0, // 表格数据总数
      values: [], // 输入框选择值
      tableData: [], // 表格数据
      inputHeight: 32, //输入框高度
    };
  },
  computed:{
    singleValue(){
      /** 单选 {userId:... userName:...} */
      let singleValue = {}
      if(this.single && this.value){
        singleValue = this.value
      }
      return singleValue
    }
  },
  watch: {
    visible(newVal, oldVal) {
      if (newVal) {
        /** 查询部门下拉树结构 */
        this.getTreeselect();
        /** 查询人员列表 */
        this.getList();
      }
    },
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    /** 初始化值 */
    this.dataInit();
  },
  mounted() {
    /** 监听文本框内容高度 */
    this.domInit();
  },
  methods: {
    dataInit() {
      /** 初始化值*/
      if(this.single){
        this.data= this.value
      }else{
      let array = [];
      if (Array.isArray(this.value) && this.value.length > 0) {
        this.value.forEach((value, key) => {
          array.push({ userId: value.id, userName: value.name });
        });
      }
      this.values = array;
      this.data = [...array];
      }
    },
    domInit() {
      if(!this.single){
        const self = this;
        /** 监听文本框内容高度*/
        const observer = new ResizeObserver((entries) => {
          entries.forEach((entry) => {
            const cr = entry.contentRect;
            self.inputHeight = (cr.height || 24) + 8;
          });
        });
        observer.observe(this.$refs.el_select__tags);
      }
    },
    getList() {
      const self = this;
      const {data} = self
      listUser(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
        this.$nextTick(function () {
          if(self.single){
            if(data && data.userId) {
              const tableRow = find(
                this.tableData,
                (o) => o.userId == data.userId
              );
              this.data = tableRow
            }
          }else{
            if(Array.isArray(data) && data.length > 0){
              data.forEach((row, index) => {
                const tableRow = find(
                  this.tableData,
                  (o) => o.userId == row.userId
                );
                self.$refs.table.toggleRowSelection(tableRow || row, true);
              });
            }
          }
        });
      });
    },
    rowClick(row, column, event) {
      if(this.single){
        this.$refs.table.clearSelection()
      }
      this.$refs.table.toggleRowSelection(row);
    },
    selectionChange(selection) {
      if(!this.single){
        this.$nextTick(function () {
          this.data = selection;
        });
      }
    },
    handleSelectChange(row){
      if(this.single){
        this.data = row
      }
    },
    handleSizeChange(size) {
      this.queryParams.pageSize = size;
      this.getList();
    },
    handleCurrentChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    remove(row, index) {
      this.values.splice(index, 1);
      this.$refs.table.toggleRowSelection(row, false);
    },
    removeTag(row, index) {
      this.data.splice(index, 1);
      this.$refs.table.toggleRowSelection(row, false);
    },
    /* 输出外部的数据，例如：[{id:1,name:'张三'}] */
    exportData(data) {
      let array = [];
      if (Array.isArray(data)) {
        forEach(data, (value, key) => {
          array.push({ id: value.userId, name: value.userName });
        });
      }
      return array;
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    cancel() {
      this.visible = false;
    },
    submitForm() {
      this.visible = false;
      if(!this.single){
        this.values = [...this.data];
      }
      this.$emit("input", this.data);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>

<style scoped>
.dialog-title {
  width: calc(100% - 20px);

  display: flex;
  align-items: center;
  justify-content: space-between;
}
.dialog-title span {
  font-size: 14px;
}
::v-deep .el-dialog__header .el-dialog__headerbtn {
  top: 10px;
}
.data-content {
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  padding: 3px 10px 3px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  min-height: 38px;
  box-sizing: border-box;
}
::v-deep .el-dialog__body {
  padding: 10px;
  height: 524px;
}

.data-wrap h5 {
  margin: 0 0 10px;
}
.opera-body {
  display: flex;
  padding: 10px 0;
}
.opera-dept {
  width: 240px;
  border: 1px solid #dcdfe6;
  margin-right: 10px;
  flex-shrink: 0;
  padding: 10px;
}
.opera-table {
  width: 830px;
}
.opera-table ::v-deep .el-form-item__label {
  font-size: 12px;
}
.query-form {
  background-color: #edf2fa;
  border: 1px solid #dfe6ec;
  padding: 6px 10px !important;
}
::v-deep .el-form-item--small.el-form-item {
  margin-bottom: 0;
}
::v-deep .data-content .el-tag {
  margin: 3px 10px 3px 0;
}
::v-deep .dialog-class {
  height: 560px !important;
}
.dialog-footer {
  text-align: right;
}

::v-deep .el-header,
::v-deep .el-main,
::v-deep .el-footer {
  padding: 0;
}
::v-deep .el-main {
  overflow-x: hidden;
}
::v-deep .el-header {
  height: auto !important;
}
::v-deep .el-footer {
  border-top: 1px solid #dfe6ec;
  padding-top: 7px;
}
::v-deep .el-container {
  height: 504px;
}
::v-deep .el-dropdown,
::v-deep .el-select {
  display: block;
}
.holder-select {
  color: #c6c6c6;
  font-size: 12px;
}
</style>
